package com.nameless.controller;


import com.alipay.api.AlipayApiException;
import com.nameless.entity.Order;
import com.nameless.utils.AlipayUtil;
import com.nameless.utils.UuidTradeNo;
import com.nameless.vo.Result;
import com.nameless.vo.pay.RequestParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author keluoyisi
 */

@RestController
@RequestMapping("/ali/payApp")
public class AliPayController {

    @Autowired
    private AlipayUtil alipayUtil;

    /**
     * 阿里支付
     *
     */
    @PostMapping("/aliPay")
    public Result aliPay(@RequestBody Order order){

        System.out.println(order);
        //该方法会返回一个支付宝二维码base4地址 然后使用vue-qs来生成该地址的二维码
        String pay = null;
        try {
            pay = alipayUtil.pay(order);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        System.out.println(pay);

        return new Result(200,"二维码",pay);

    }

    /**
     * 验证支付宝支付成功
     */
    @PostMapping("/return")
    public Result payReturn(@RequestBody Order order) throws AlipayApiException {
        Result aReturn = alipayUtil.getReturn(order);
        return aReturn;
    }

    /**
     * 验证支付宝支付成功
     */
    @GetMapping("/return/{orderNo}")
    public Result payReturn(@PathVariable String orderNo) throws AlipayApiException {
        Result aReturn = alipayUtil.getReturn(orderNo);
        return aReturn;
    }

    /**
     * 阿里支付
     *
     */
    @PostMapping("/createAliPay")
    public Result<Map<String, Object>> createAliPay(@RequestBody RequestParams order){

        if (order.getOrderNo() == null) {
            // 自动生成单号
            String orderNum = UuidTradeNo.getOrderNum(order.getClientId());
            order.setOrderNo(orderNum);
        }

        System.out.println(order);
        //该方法会返回一个支付宝二维码base4地址 然后使用vue-qs来生成该地址的二维码
        Map<String, Object> pay = null;
        try {
            pay = alipayUtil.pay(order.getOrderNo(),order.getMoney());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        System.out.println(pay);

        return new Result<>(200,"二维码",pay);

    }

}